﻿using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevExpress.Data;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;

namespace ConfExpert.Forms.Siparisler
{
    public partial class InteractiveOrder : XForm
    {
        public InteractiveOrder()
        {
            InitializeComponent();
        }

        private void InteractiveOrder_Load(object sender, EventArgs e)
        {
            RepositoryItemComboBox riModel = new RepositoryItemComboBox();
            riModel.Items.AddRange(new object[] { "CARSDE_1B", "CBRSDG_N", "CGRSDR_M1", "CGRNDR_PP1" });
            //riModel.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;

            DataSet d = ExecuteDataSet("GetInteractive");
            DataTable Arts = d.Tables[0].Copy();
            DataTable Execs = d.Tables[1].Copy();
            gridView1.Init(Arts);
            gridView2.Init(Execs);

            gridView2.DataTable().AddAutoIncrementalColumn("idx");
            gridView2.DataTable().PrimaryKey = new DataColumn[] { gridView2.DataTable().Columns["idx"] };

            gridView1.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
            gridView2.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
            gridView2.Columns["Model"].ColumnEdit = riModel;

            ((RepositoryItemComboBox)gridView2.Columns["Model"].ColumnEdit).TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;

            gridView2.AddColumn("Q0", typeof(float), "Adet * IIF(Model='CGRNDR_PP1',1.01, IIF(Model='CARSDE_1B',1.40, IIF(Model='CBRSDG_N', 1.45, IIF(Model='CGRSDR_M1', 1.34, 0))))");
            gridView2.AddColumn("Q1", typeof(float), "Adet * IIF(Model='CGRNDR_PP1',0.13, IIF(Model='CARSDE_1B',0.14, IIF(Model='CGRSDR_M1', 0.18, 0)))");
            gridView2.AddColumn("Q2", typeof(float), "Adet * IIF(Model='CGRNDR_PP1',0.13, IIF(Model='CGRSDR_M1', 0.14, 0))");

            AddScan(gridView2, "S0", "S1", "S2");
            gridView2.SetCaptions("S0:Sc0", "S1:Sc1", "S2:Sc2");
            gridView2.CustomUnboundColumnData -= new DevExpress.XtraGrid.Views.Base.CustomColumnDataEventHandler(gvx_CustomUnboundColumnData);
            gridView2.CalcRowHeight -= new RowHeightEventHandler(gridview_CalcRowHeight);

            gridView2.CustomUnboundColumnData += new DevExpress.XtraGrid.Views.Base.CustomColumnDataEventHandler(gvx_CustomUnboundColumnData);
            gridView2.CalcRowHeight += new RowHeightEventHandler(gridview_CalcRowHeight);

            gridView2.YanYanaGetirSoluna("INT3", "Model", "Adet",
                "S0", "Corpo", "Q0",
                "S1", "INT1", "Q1",
                "S2", "INT2", "Q2");
            gridView2.MakeColumnInvisible("idx", "INT3");
            gridView2.FormatAsNumber(1, "Q0", "Q1", "Q2");
            gridView2.FormatAsNumber(0, "Adet");

            gridView1.FormatAsNumber(1, "IDLE", "A", "G", "Toplam", "Kalan");
            gridView1.RowCellStyle += gridView1_RowCellStyle;

            gridView1.AddSummary("IDLE", "A", "G", "Toplam", "Kalan");
            gridView2.AddSummary("Adet");
            gridView1.MakeReadOnly();

            bbiHesapla.ItemClick += bbiHesapla_ItemClick;
            gridView2.OptionsView.EnableAppearanceEvenRow = gridView2.OptionsView.EnableAppearanceOddRow = false;
            gridView2.RowCellStyle += gridView2_RowCellStyle;

            gridView2.ShowingEditor += gridView2_ShowingEditor;
            gridView1.FocusedRowChanged += gridView1_FocusedRowChanged;
            gridView2.ShowFindPanel();
            gridView2.RowCellClick += gridView2_RowCellClick;
            BestFit();
        }

        int GetId(string Val)
        {
            DataRow[] dr = AppSession.Lookups.V_Kumas.Select("Name='" + gridView2.GetFocusedRowCellValue(Val).ToString() + "'");
            if (dr.Length > 0)
                if (dr[0]["ProductId"] != DBNull.Value)
                    return dr[0]["ProductId"].ToInt();

            return 0;
        }

        void gridView2_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            switch (gridView2.FocusedColumn.FieldName)
            {
                case "S0": Goster(GetId("Corpo")); break;
                case "S1": Goster(GetId("INT1")); break;
                case "S2": Goster(GetId("INT2")); break;

                default:
                    Notify(" ");
                    object o = gridView2.GetFocusedValue();
                    if (o != DBNull.Value)
                    {

                        string art = o.ToStr();
                        DataRow[] dr = AppSession.Lookups.V_Kumas.Select("Name='" + art + "'");
                        if (dr.Length > 0)
                            if (dr[0]["ProductId"] != DBNull.Value)
                            {
                                int ProductId = dr[0]["ProductId"].ToInt();
                                DataRow[] dr2 = gridView1.DataTable().Select("ProductId=" + ProductId);
                                if (dr2.Length > 0)
                                    if (dr2[0]["ProductId"] != DBNull.Value)
                                        Notify(string.Format(" {0} |  Kalan: {1:#,##0.0}", art, dr2[0]["Kalan"].ToDecimal()));
                            }
                    }
                    break;
            }
        }

        void BestFit()
        {
            gridView1.BestFitColumns();
            gridView2.BestFitColumns();
            gridView1.Columns["PRO"].Width = 150;
            gridView2.Columns["S0"].Width =
            gridView2.Columns["S1"].Width =
            gridView2.Columns["S2"].Width = 34;

            //OPS.. burası çalışır mı kontrol et
            gridView1.FocusedRowHandle = gridView1.LocateByValue(0, gridView1.Columns["ProductId"], ProductId);
            if (idx > 0)
                gridView2.FocusedRowHandle = gridView2.LocateByValue(0, gridView2.Columns["idx"], idx);
            else
                gridView2.FocusedRowHandle = GridControl.NewItemRowHandle;
        }

        public void gvx_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.ListSourceRowIndex > -1 &&
                e.Column.FieldName.StartsWith("S") && e.Column.FieldName.Length == 2)
                if (e.IsGetData)
                {
                    string col = e.Column.FieldName.Replace("S", "Product") + "Id";

                    if (((DataRowView)e.Row)[col].ToInt() > 0)
                    {
                        DataRow[] dr = AppSession.Lookups.V_Kumas.Select("ProductId=" + ((DataRowView)e.Row)[col].ToString());
                        if (dr.Length > 0)
                            if (dr[0]["PhotoMikro"] != DBNull.Value)
                                e.Value = dr[0]["PhotoMikro"];
                    }
                }
        }
        /*
        public void gvx_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            DataRow[] dr;
            if (e.ListSourceRowIndex > -1 &&
                e.Column.FieldName.StartsWith("S") && e.Column.FieldName.Length == 2)
                if (e.IsGetData)
                    switch (e.Column.FieldName)
                    {
                        case "S0":
                            dr = AppSession.Lookups.V_Kumas.Select("Name='" + ((DataRowView)e.Row)["Corpo"].ToString() + "'");
                            if (dr.Length > 0)
                                if (dr[0]["PhotoMikro"] != DBNull.Value)
                                    e.Value = dr[0]["PhotoMikro"];
                            break;

                        case "S1":
                            dr = AppSession.Lookups.V_Kumas.Select("Name='" + ((DataRowView)e.Row)["INT1"].ToString() + "'");
                            if (dr.Length > 0)
                                if (dr[0]["PhotoMikro"] != DBNull.Value)
                                    e.Value = dr[0]["PhotoMikro"];
                            break;

                        case "S2":
                            dr = AppSession.Lookups.V_Kumas.Select("Name='" + ((DataRowView)e.Row)["INT2"].ToString() + "'");
                            if (dr.Length > 0)
                                if (dr[0]["PhotoMikro"] != DBNull.Value)
                                    e.Value = dr[0]["PhotoMikro"];
                            break;

                    }
        }
        */
        void AddScan(GridView gridview, params string[] FieldNames)
        {
            RepositoryItemPictureEdit ri = new RepositoryItemPictureEdit();
            ri.SizeMode = PictureSizeMode.Clip;
            ri.NullText = " ";

            List<GridColumn> cols = new List<GridColumn>();
            foreach (string FieldName in FieldNames)
            {
                GridColumn col = new GridColumn();
                col.FieldName = FieldName;
                col.UnboundType = UnboundColumnType.Object;
                col.ColumnEdit = ri;
                cols.Add(col);
            }
            gridview.Columns.AddRange(cols.ToArray());
        }

        /*
        void XForm_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.RowHandle > -1)
                if ((e.Column.FieldName.StartsWith("S") && e.Column.FieldName.Length == 2) &&
                    (e.CellValue == DBNull.Value || e.CellValue == null))
                {
                    //e.DisplayText = "X";
                    e.Graphics.DrawImageUnscaled(notready, e.Bounds.X + (e.Bounds.Width / 2 - 14), e.Bounds.Y);
                    e.Handled = true;
                }
        }
        */

        void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            //gridView2.RefreshData();
        }

        void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.Column.FieldName == "Kalan" && e.RowHandle > -1)
                if (e.CellValue.ToDecimal() < 0)
                    e.Appearance.ForeColor = Color.Red;
        }

        void gridView2_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            switch (gridView2.FocusedColumn.FieldName)
            {
                case "INT1": e.Cancel = gridView2.GetFocusedRowCellDisplayText("Q1") != string.Empty; break;
                case "INT2": e.Cancel = gridView2.GetFocusedRowCellDisplayText("Q2") != string.Empty; break;
            }
        }

        void gridView2_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            string Art = gridView1.GetFocusedRowCellDisplayText("ProductId");
            //if (e.CellValue != null)
            //{
            //    if (e.CellValue.ToString() == Art)
            //        e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
            //}

            switch (gridView2.GetRowCellDisplayText(e.RowHandle, "Model"))
            {
                case "CARSDE_1B":
                    switch (e.Column.FieldName)
                    {
                        case "Corpo":
                        case "INT1":
                            e.Appearance.BackColor = Color.Beige;
                            break;
                    }
                    break;

                case "CBRSDG_N":
                    switch (e.Column.FieldName)
                    {
                        case "Corpo":
                            e.Appearance.BackColor = Color.Beige;
                            break;
                    }
                    break;

                case "CGRSDR_M1":
                case "CGRNDR_PP1":
                    switch (e.Column.FieldName)
                    {
                        case "Corpo":
                        case "INT1":
                        case "INT2":
                            e.Appearance.BackColor = Color.Beige;
                            break;
                    }
                    break;

            }
        }

        int idx = 0, ProductId = 0;
        void bbiHesapla_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView2.EndEditing();
            ProductId = gridView1.GetFocusedRowCellValue("ProductId").ToInt(-1);
            idx = gridView2.GetFocusedRowCellValue("idx").ToInt(-1);

            gridView2.Update("idx,Model,Corpo,INT1,INT2,INT3,Adet", "InteractiveOrder");

            DataSet d = ExecuteDataSet("GetInteractive");
            DataTable Arts = d.Tables[0].Copy();
            DataTable Execs = d.Tables[1].Copy();
            gridView1.RefreshDataSource(Arts, true);
            gridView2.RefreshDataSource(Execs, true);
            BestFit();
        }

    }
}
